import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(urlPatterns = {"/hello"})
public class HelloServlet extends HttpServlet {
    private static final String URL = "jdbc:h2:~/test_student;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String NAME = "sa";
    private static final String PASSWORD = "";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try (Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD)) {
            Statement stmt = conn.createStatement();
            //插入数据到数据库
            stmt.executeUpdate(
                    "CREATE TABLE IF NOT EXISTS `student` (" +
                            "  `id` int(11) unsigned NOT NULL AUTO_INCREMENT," +
                            "  `courseName` varchar(100) NOT NULL," +
                            "  `score` int(3) NOT NULL," +
                            "  PRIMARY KEY (`id`)" +
                            ");"
            );
            ResultSet rset = stmt.executeQuery("select * from student");
            if(!rset.next()) {
                stmt.executeUpdate(
                        "insert into `student` (`id`,`courseName`,`score`) values (1, 'javaee', 99);" +
                                "insert into `student` (`id`,`courseName`,`score`) values (2, 'computer', 98);" +
                                "insert into `student` (`id`,`courseName`,`score`) values (3, 'Analysis', 97);"
                );
            }
            resp.sendRedirect("/test/student.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
